use salvo::{handler, Request};
use uuid::Uuid;
use crate::domain::dto::login_dto::{CaptchaResponse, UserLoginRequest, UserLoginResponse};
use crate::domain::dto::{result_to_res, Res, ResObj};
use crate::domain::error::AccountError;
use crate::service::{redis_service, user_service};
use crate::utils::tool::create_captcha;

/// login 登录
/// api_server::service::user_service: 生成的密码:
#[handler]
pub async fn login(request: &mut Request) -> Res<UserLoginResponse> {
    let param = request.parse_json::<UserLoginRequest>()
        .await
        .map_err(|err| {
            println!("{}", err);
            ResObj::fail_with_error(AccountError::RequestError)
        })?;
    tracing::info!("登录请求参数: {:?}", param);
    let res = user_service::user_login(param).await;
    result_to_res(res)
}

/// captcha 验证码
#[handler]
pub async fn captcha() -> Res<CaptchaResponse> {
    if let (captcha_str, Some(base64)) = create_captcha() {
        let uuid = Uuid::new_v4().to_string();
        // 存入Redis
        redis_service::set_ex(&uuid, captcha_str.to_lowercase(), 300).unwrap();
        tracing::info!("验证码: {}", &captcha_str);
        Ok(ResObj::ok(Some(CaptchaResponse {
            captcha_enabled: Some(false),
            img: format!("data:image/gif;base64,{}", base64),
            uuid,
        })))
    } else {
        Err(ResObj::fail_with_error(AccountError::CaptchaError))
    }
}